import {onBeforeUnmount, ref, toRaw, watch} from "vue";
import {useStore} from "@/stores";

export function useActiveMenu(name: string, cb: any) {
    const store = useStore();
    const callback = ref(cb);

    const activeMenu = () => {
        const item = store.getActiveMenu(name);
        return item ? toRaw(item) : '';
    }

    const updateActiveMenu = (path: any) => {
        if (path) {
            store.updateActiveMenu(name, path);
        }
    }

    const setActiveMenuCallback = (cb: any) => {
        callback.value = cb;
    }

    const stopWatch = watch(
        () => (store.activeMenu[name]),
        (newVal) => {
            const newRaw =  toRaw(newVal);
            if (callback.value) {
                callback.value(newRaw);
            }
        }, {immediate: true}
    );

    onBeforeUnmount(() => {
        stopWatch();
    })

    return {
        activeMenu,
        updateActiveMenu,
        setActiveMenuCallback,
    }
}
